package com.hupu.jrs.util

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * Created by sll on 2015/3/9.
 */
object SecurityUtil {

    fun getMd5ByteByFile(file: File): String {
        var fileInputStream: FileInputStream? = null
        try {
            fileInputStream = FileInputStream(file)
            val md = MessageDigest.getInstance("MD5")
            fileInputStream = FileInputStream(file)
            val buffer = ByteArray(2048)
            var length: Int
            while ((length = fileInputStream.read(buffer)) != -1) {
                md.update(buffer, 0, length)
            }
            //32位加密
            return bytesToHexString(md.digest())
        } catch (e: Exception) {
            return ""
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close()
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 使用MD5算法对传入的key进行加密并返回。
     */
    fun getMD5(key: String): String {
        var cacheKey: String
        try {
            val mDigest = MessageDigest.getInstance("MD5")
            mDigest.update(key.toByteArray())
            cacheKey = bytesToHexString(mDigest.digest())
        } catch (e: NoSuchAlgorithmException) {
            cacheKey = key.hashCode().toString()
        }

        return cacheKey
    }

    private fun bytesToHexString(bytes: ByteArray): String {
        val sb = StringBuilder()
        for (i in bytes.indices) {
            val hex = Integer.toHexString(0xFF and bytes[i].toInt())
            if (hex.length == 1) {
                sb.append('0')
            }
            sb.append(hex)
        }
        return sb.toString()
    }
}
